package com.zxy.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

@Service
public class Test2Service implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ThreadHandle threadHandle;

    private Thread t;

    static final Logger logger = LoggerFactory.getLogger( Test2Service.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("------------------onApplicationEvent--------------------");
        //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
        if(event.getApplicationContext().getParent() == null){//root application context 没有parent，他就是老大.
            //需要执行的逻辑代码，当spring容器初始化完成后就会执行该方法。
            t = new Thread(threadHandle);
            t.start();
        }
    }

    //判断是否工作
    public boolean isWork(){
        return threadHandle.isWork() ;
    }

    //开始工作
    public void startWork(){
        if( !threadHandle.isWork() ){
            threadHandle.startWork();
            t = new Thread(threadHandle);
            t.start();
        }
    }

    //停止工作
    public void stopWork(){
        if( threadHandle.isWork() ){
            threadHandle.stopWork();
        }
    }


    public Test2Service(){
        System.out.println(" -------------------- init TestService -------------- ");

    }

}
